<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="scheduleName">
        <el-input
          v-model="queryParams.scheduleName"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker clearable size="small"
                        v-model="queryParams.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker clearable size="small"
                        v-model="queryParams.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="运行频率" prop="rate">
        <el-input
          v-model="queryParams.rate"
          placeholder="请输入运行频率"
          clearable
          onkeyup="value=value.replace(/[^\d]/g,'')"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="频率单位" prop="rateUnit">

        <el-select v-model="queryParams.rateUnit" placeholder="请选择频率单位" clearable :style="{width: '100%'}">
          <el-option
            v-for="dict in contentUnitOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>

      </el-form-item>
      <el-form-item label="是否启动" prop="isStartUp">
        <el-select v-model="queryParams.isStartUp" placeholder="是否启动" clearable :style="{width: '100%'}">
          <el-option
            v-for="dict in taskType"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['vims:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['vims:task:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['vims:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:task:export']"
        >获取数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务名称" align="center" prop="scheduleName" />
      <el-table-column label="开始日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate,'{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运行频率" align="center" prop="rate" />
      <el-table-column label="频率单位" align="center" prop="rateUnit" :formatter="contentUnitFormat"/>
      <el-table-column label="状态" align="center" prop="isStartUp" :formatter="contentTypeFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleDetails(scope.row)"
            v-hasPermi="['vims:task:info']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleStop(scope.row)"
            v-hasPermi="['vims:task:info']"
          >停止</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['vims:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加 -->
    <el-dialog id="addDate":title="title" :visible.sync="open" width="80%" append-to-body>
      <el-row :gutter="15">
        <el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px">
          <el-col :span="24">
            <el-form-item label="任务名称" prop="scheduleName">
              <el-input v-model="form.scheduleName" placeholder="请输入任务名称" :maxlength="12" show-word-limit
                        clearable prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="form.startDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择开始日期" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="form.endDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择结束日期" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker v-model="form.startTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              :picker-options='{"selectableRange":"00:00:00-23:59:59"}' :style="{width: '100%'}"
                              placeholder="请选择时间选择" clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker v-model="form.endTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              :picker-options='{"selectableRange":"00:00:00-23:59:59"}' :style="{width: '100%'}"
                              placeholder="请选择时间选择" clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行频率" prop="rate">
              <el-input v-model="form.rate" placeholder="请输入运行频率" clearable :style="{width: '100%'} " onkeyup="value=value.replace(/[^\d]/g,'')">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="频率单位" prop="rateUnit">
              <el-select v-model="form.rateUnit" placeholder="请选择频率单位" clearable :style="{width: '100%'}">
                <el-option
                  v-for="dict in contentUnitOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择通道" prop="selectChannel">
              <el-cascader v-model="selectChannel" placeholder="请选择选择通道" clearable
                           :style="{width: '100%'}"
                           :options="channelOptions"
                           :show-all-levels="false"
                           :props="{ multiple: true, expandTrigger: 'hover' ,value: 'channelCode',label:'name'}"
                           filterable>
                <template slot-scope="{ node, data }">
                  <span>{{ data.name }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="预设点" prop="selectPre">
              <el-button type="primary" icon="el-icon-thumb" size="medium" v-on:click="getPresetPointListButton">查看预设点</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详情页面 -->
    <el-dialog id="handleDetails" :title="title" :visible.sync="openDetails" width="80%" append-to-body>
      <el-row :gutter="15">
        <el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px">
          <el-col :span="24">
            <el-form-item label="任务名称" prop="scheduleName">
              <el-input v-model="form.scheduleName" placeholder="请输入任务名称" :maxlength="12" show-word-limit
                        clearable prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="form.startDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择开始日期" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="form.endDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择结束日期" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker v-model="form.startTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              :picker-options='{"selectableRange":"00:00:00-23:59:59"}' :style="{width: '100%'}"
                              placeholder="请选择时间选择" clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker v-model="form.endTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              :picker-options='{"selectableRange":"00:00:00-23:59:59"}' :style="{width: '100%'}"
                              placeholder="请选择时间选择" clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行频率" prop="rate">
              <el-input v-model="form.rate" placeholder="请输入运行频率" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="频率单位" prop="rateUnit">
              <el-select v-model="form.rateUnit" placeholder="请选择频率单位" clearable :style="{width: '100%'}">
                <el-option
                  v-for="dict in contentUnitOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
        <br>
        <el-table
          :data="form.channelPresetInfoVOList"
          style="width: 100%">

          <el-table-column
            label="通道名称" prop="channelName"
            align="center">
          </el-table-column>
          <el-table-column
            label="预设节点" prop="channelPreset" align="center">
          </el-table-column>
        </el-table>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 预设节点页面 -->
    <el-dialog id="handlePreset" :title="title" :visible.sync="openPreset" width="80%" append-to-body>
      <el-table v-loading="loading" :data="presetPointList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="通道名称" align="center" prop="channelName" />
        <el-table-column label="选择预设节点" align="center" prop="presetModels">
          <template slot-scope="scope">
            <el-select v-model="scope.row.channelPreset" placeholder="请选择">
              <el-option
                v-for="item in scope.row.presetModels"
                :key="item.index"
                :label="item.name"
                :value="item.index">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.index }}</span>
              </el-option>
            </el-select>
          </template>

        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="presetButton">确 定</el-button>
        <el-button @click="cancelPreset">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  exportTask,
  getVimsToken,
  getVIMSChannelTree,
  getVIMSPresetPoints,
  stopTask
} from "@/api/file/task";
import task from "@/views/file/flie/task";
import {getToken} from "@/utils/auth";

export default {
  name: "Task",
  components: {
  },
  data() {
    return {
      openPreset: false,
      channelPreNode: null,
      selectChannel: [],
      channelOptions: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNumer: 1,
        pageSize: 10,
        scheduleName: null,
        startDate: null,
        endDate: null,
        startTime: null,
        endTime: null,
        rate: null,
        rateUnit: null,
        scheduleId: null,
        channelPresetInfoList: null,
        token: null,
        isStartUp: null
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //时间字典类型
      contentUnitOptions: [],
      // 详情页面
      openDetails: false,

      // token
      token: null,
      env_api: 'http://119.3.125.255:8080',
      //
      vimsParams:{
        appKey: '77be010f7aa04abcb0888b2015aee0dc',
        secret: '35e2748cda3a49dc88c7f4fbb0b49672'
      },
      presetPointsParams: {
        channelCodes: null,
      },
      presetPointList: [],
      presetPointsTotal: null,
      vimsToken: null,
      taskType:null
    };
  },
  beforeCreate() {

  },
  created() {

    this.getDicts("vims_time").then(response => {
      this.contentUnitOptions = response.data
    })
    this.getDicts("vims_task").then(response => {
      this.taskType = response.data
    })
    this.getList()
    this.getChannelTree()


  },
  methods: {
    // 获取预设点按钮
    getPresetPointListButton(){
      let channelCodes = []
      if (this.selectChannel == null ||this.selectChannel.length <=0){
        this.$message({
          message: '请选择预设点',
          type: 'warning'
        })
        return
      }
      let i=0
      for (;i<this.selectChannel.length;i++){
        var node = this.selectChannel[i].pop()
        if (node == null){
          continue
        }
        channelCodes.push(node)
        this.selectChannel[i].push(node)
      }
      console.log("获取预设点")
      console.log(channelCodes)
      //开始查询预设结点
      this.presetPointsParams.channelCodes = channelCodes;
      this.openPreset = true
      this.loading = true
      this.getPresetPoints()


    },
    // 确定阈值节点按钮
    presetButton(){
      console.log("PresetButton")
      console.log(this.presetPointList)
      let i;
      var channelPresetInfoVOList = [];
      for (i=0;i<this.presetPointList.length;i++){
        if (this.presetPointList[i].hasOwnProperty("channelPreset")){
          var cur  = {channelCode:this.presetPointList[i].channelCode,channelName:this.presetPointList[i].channelName,channelPreset:this.presetPointList[i].channelPreset}

          channelPresetInfoVOList.push(cur)
        }
      }
      this.form.channelPresetInfoVOList = channelPresetInfoVOList
      this.openPreset = false

    },
    //查询预置点列表
    getPresetPoints(){
      //合成urlChild = ids=1&ids=2&ids=

      console.log("查询参数 ",this.presetPointsParams.channelCodes)
      getVIMSPresetPoints(this.presetPointsParams.channelCodes).then(response => {
        console.log("response",response)
        console.log("response ",response)
        this.presetPointList = response.data.dataList;
        this.presetPointsTotal = response.data.totalNum;
        this.title = "选择预设点"
        this.loading = false;
      })
    },
    // 获取通道信息
    getChannelTree(){
      console.log("getChannelTree ")
      getVIMSChannelTree().then(response => {
        console.log("response",response)
        this.channelOptions = response;

      })

    },

    // 时间类型字典翻译
    contentUnitFormat(row, column) {
      return this.selectDictLabel(this.contentUnitOptions, row.rateUnit);
    },
    //任务状态
    contentTypeFormat(row, column) {
      return this.selectDictLabel(this.taskType, row.isStartUp);
    },
    // 处理时间
    parseTimes(date){
      return ""+date.toString();
    },


    /** 查询【请填写功能名称】列表 */
    getList() {
      // this.getToken()
      console.log("getList")
      this.loading = true;
      listTask(this.queryParams).then(response => {
        console.log("getList response",response)
        this.taskList = response.data.dataList
        console.log("getList data",this.taskList)

        this.total = response.data.totalNum
        this.loading = false
      })

    },
    cancelPreset() {
      this.openPreset = false
      this.this.form.channelPresetInfoVOList = []
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openDetails = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        channelPresetInfoVOList: null,
        scheduleName: null,
        startDate: null,
        endDate: null,
        startTime: null,
        endTime: null,
        rate: null,
        rateUnit: null,
        scheduleId: null,

      }
      this.selectChannel = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.schedulename)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增任务";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const schedulename = row.schedulename || this.ids
      getTask(schedulename).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log("提交按钮")
      console.log(this.form)
      // if (this.verifyTheSubmittedData()){
      //
      // }
      addTask(this.form).then(response => {
        this.msgSuccess("新增成功");
        this.open = false;
        this.getList();
      })
      this.selectChannel = []



    },
    // 验证提交的数据
    verifyTheSubmittedData(){
      if (this.form.scheduleName == null || this.form.scheduleName === ''){
        this.$message({
          message: '任务名称为空',
          type: 'warning'
        });
        return false
      }
      // if (this.startDate == null){
      //   this.$message({
      //     message: '开始日期为空',
      //     type: 'warning'
      //   });
      //   return false
      // }
      // if (this.endDate == null){
      //   this.$message({
      //     message: '结束日期为空',
      //     type: 'warning'
      //   });
      //   return false
      // }
      // if (this.startTime == null){
      //   this.$message({
      //     message: '开始时间为空',
      //     type: 'warning'
      //   });
      //   return false
      // }
      // if (this.endTime == null){
      //   this.$message({
      //     message: '结束时间为空',
      //     type: 'warning'
      //   });
      //   return false
      // }
      if (!this.checkEndTime(this.form.startDate,this.form.endDate)){
        this.$message({
          message: '开始日期必须早于结束日期',
          type: 'warning'
        });
        return false
      }
      if (!this.checkEndTime(this.form.startTime,this.form.endTime)){
        this.$message({
          message: '开始时间必须早于结束时间',
          type: 'warning'
        });
        return false
      }
      if (this.this.form.channelPresetInfoVOList == null || this.this.form.channelPresetInfoVOList.length == 0){
        this.$message({
          message: '未选择预设点',
          type: 'warning'
        });
        return false
      }
      return  true


    },
    checkEndTime(startTime,endTime){

      var start=new Date(startTime.replace("-", "/").replace("-", "/"));

      var end=new Date(endTime.replace("-", "/").replace("-", "/"));
      if(end<start){
        return false;
      }
      return true;
    },
    // 详情按钮操作
    handleDetails(row){
      this.title = "任务详情"
      this.openDetails = true


      this.form = row
      console.log("任务详情")
      console.log(this.form.channelPresetInfoList)

    },
    //停止按钮
    handleStop(row){
      const ids = row.scheduleId;
      this.$confirm('是否确认删除【截图任务】编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {

        return stopTask(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.scheduleId || this.ids;
      this.$confirm('是否确认删除【任务】编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {

        return delTask(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("成功停止");
      }).catch(() => {});
    },
    /** 获取数据按钮操作 */
    handleExport() {
      // this.$http.get('http://192.168.1.140:80/openapi/schedule/capture/list',
      //   {params:this.queryParams}
      // ).then(function (resp) {
      //   console.log(resp)
      //   this.taskList = resp.data
      // })
    }
  }
};
</script>
